package com.jw.qme.service.impl;

import com.jw.qme.domain.dto.HeartbeatRequestDTO;
import com.jw.qme.domain.vo.HeartbeatVO;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

@Service
public class HeartbeatService {

    // 存储用户最后心跳时间
    private final ConcurrentHashMap<String, Long> userLastHeartbeat = new ConcurrentHashMap<>();
    
    // 心跳超时时间（毫秒）
    private static final long HEARTBEAT_TIMEOUT = 60000; // 1分钟

    public HeartbeatVO handleHeartbeat(HeartbeatRequestDTO request) {
        // 更新用户心跳时间
        userLastHeartbeat.put(request.getUserId(), System.currentTimeMillis());
        
        // 返回成功响应
        return new HeartbeatVO(true, "Heartbeat received", System.currentTimeMillis());
    }

    /**
     * 检查用户是否在线
     */
    public boolean isUserOnline(String userId) {
        Long lastHeartbeatTime = userLastHeartbeat.get(userId);
        if (lastHeartbeatTime == null) {
            return false;
        }
        return (System.currentTimeMillis() - lastHeartbeatTime) <= HEARTBEAT_TIMEOUT;
    }

    /**
     * 获取用户在线状态
     */
    public HeartbeatVO getUserStatus(String userId) {
        boolean online = isUserOnline(userId);
        return new HeartbeatVO(online, online ? "Online" : "Offline", System.currentTimeMillis());
    }


    // JS 中对应的心跳检测函数
//    function sendHeartbeat() {
//        fetch('/api/heartbeat', {
//                method: 'POST',
//                headers: {
//            'Content-Type': 'application/json'
//        },
//        body: JSON.stringify({userId: currentUser.id})
//    });
//    }
//
//    // 每30秒发送一次心跳
//    setInterval(sendHeartbeat, 30000);

}
